package com.bnz.service.impl;

import com.bnz.mapper.ClassesMapper;
import com.bnz.mapper.StudentMapper;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.util.PageResult;
import com.bnz.vo.StudentVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public List<Student> findAll() {
        //查询所以学生
        List<Student> students = studentMapper.selectAll();
        //遍历学生的同时将cname赋予cid
        for (Student student : students) {
            student.setCname(classesMapper.selectByPrimaryKey(student.getCid()).getCname());
        }
        //将数据返回
        return students;
    }

    //分页查询
    @Override
    public PageResult<Student> findByPage(int page, int pagesize) {
        //开始分页
        PageHelper.startPage(page,pagesize);
        //定义查询条件
        Example example = new Example(Student.class);
        // Example.Criteria criteria = example.createCriteria();
        //封装查询条件
        List<Student> students = studentMapper.selectByExample(example);
        for (Student student : students) {
            student.setCname(classesMapper.selectByPrimaryKey(student.getCid()).getCname());
        }
        //转换为PageInfo
        PageInfo<Student> pageInfo = new PageInfo<>(students);
        //返回PageResult对象
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    //条件查询带分页
    @Override
    public PageResult<Student> search(int page, int pagesize, StudentVo studentVo) {
        //开始分页
        PageHelper.startPage(page,pagesize);
        //定义查询条件
        Example example = new Example(Student.class);
        Example.Criteria criteria = example.createCriteria();
        //封装查询条件
        if(!StringUtils.isEmpty(studentVo.getSname())){
            criteria.andLike("sname","%"+studentVo.getSname() + "%");
        }
        if(!StringUtils.isEmpty(studentVo.getAddr())){
            criteria.andLike("addr","%"+studentVo.getAddr() + "%");
        }
        if(studentVo.getCid() != 0){
            criteria.andEqualTo("cid",studentVo.getCid());
        }
        //进行实例查询
        List<Student> students = studentMapper.selectByExample(example);
        for (Student student : students) {
            student.setCname(classesMapper.selectByPrimaryKey(student.getCid()).getCname());
        }
        //转换为PageInfo
        PageInfo<Student> pageInfo = new PageInfo<>(students);
        //返回PageResult对象
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }
}